package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.mapper.EnvironmentMapper;
import com.innovation.ic.b1b.monitor.base.model.Environment;
import com.innovation.ic.b1b.monitor.base.pojo.DropDownPojo;
import com.innovation.ic.b1b.monitor.base.pojo.EnvironmentPojo;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ElasticsearchService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.EnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MongodbService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MySqlService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RabbitmqService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RedisService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RelEnvironmentServiceService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RelSystemEnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.SqlServerService;
import com.innovation.ic.b1b.monitor.base.vo.DropDownVo;
import com.innovation.ic.b1b.monitor.base.vo.EnvironmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EnvironmentServiceImpl extends ServiceImpl<EnvironmentMapper, Environment> implements EnvironmentService {

    @Resource
    private RelSystemEnvironmentService relSystemEnvironmentService;

    @Resource
    private RelEnvironmentServiceService relEnvironmentServiceService;

    @Resource
    private ServiceService serviceService;

    @Resource
    private MySqlService mySqlService;

    @Resource
    private SqlServerService sqlServerService;

    @Resource
    private ElasticsearchService elasticsearchService;

    @Resource
    private MongodbService mongodbService;


    @Resource
    private RabbitmqService rabbitmqService;


    @Resource
    private RedisService redisService;


    @Override
    public ServiceResult addEnvironment(EnvironmentVo environmentVo) {
        ServiceResult serviceResult = new ServiceResult();
        Integer id = environmentVo.getId();
        Environment environment = new Environment();
        BeanUtil.copyProperties(environmentVo, environment);
        QueryWrapper<Environment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", environment.getName());
        if (id == null) {
            //验重,环境名字唯一
            List<Environment> environments = this.baseMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(environments)) {
                this.baseMapper.saveReturnId(environment);
                environmentVo.setEnvId(environment.getId());
            } else {
                environmentVo.setEnvId(environments.get(0).getId());
            }
        } else {
            //验重,环境名字唯一
            queryWrapper.ne("id", id);
            List<Environment> environments = this.baseMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(environments)) {
                this.baseMapper.updateById(environment);
            }
            environmentVo.setEnvId(id);
        }
        boolean contain = relSystemEnvironmentService.save(environmentVo);
        if (contain) {
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage("关联重复,请重新选择");
            return serviceResult;
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("成功");
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEnvironment(EnvironmentVo environmentVo) {
        Integer id = environmentVo.getId();
        this.baseMapper.deleteById(id);
        //删除系统和环境关联表
        relSystemEnvironmentService.deleteByEnvironmentId(id);
        //同时删除环境下的服务
        serviceService.deleteByEnvironmentId(id);
        //删除mysql和msqlserver
        mySqlService.deleteByEnvironmentId(id);
        sqlServerService.deleteByEnvironmentId(id);
        //删除es和mongodb
        elasticsearchService.deleteByEnvironmentId(id);
        mongodbService.deleteByEnvironmentId(id);
        //删除rabbitmq和redis
        rabbitmqService.deleteByEnvironmentId(id);
        redisService.deleteByEnvironmentId(id);
    }

    @Override
    public EnvironmentPojo findById(EnvironmentVo environmentVo,Boolean mainDb) {
        return this.baseMapper.findById(environmentVo.getId());
    }

    @Override
    public ServiceResult<PageInfo<EnvironmentPojo>> findByPage(EnvironmentVo environmentVo,Boolean mainDb) {
        ServiceResult<PageInfo<EnvironmentPojo>> serviceResult = new ServiceResult<>();
        PageHelper.startPage(environmentVo.getPageNo(), environmentVo.getPageSize());
        List<EnvironmentPojo> environmentPojoList = this.baseMapper.findByPage(environmentVo);
        PageInfo<EnvironmentPojo> pageInfo = new PageInfo<>(environmentPojoList);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public void deleteBySystemId(Integer systemId) {
        if (systemId == null) {
            return;
        }
        List<Integer> environmentIds = relSystemEnvironmentService.findBySystemId(systemId);
        if (CollectionUtils.isEmpty(environmentIds)) {
            return;
        }
        for (Integer environmentId : environmentIds) {
            EnvironmentVo environmentVo = new EnvironmentVo();
            environmentVo.setId(environmentId);
            this.deleteEnvironment(environmentVo);
        }
    }

    @Override
    public List<EnvironmentPojo> dropDown(EnvironmentVo environmentVo,Boolean mainDb) {
        List<EnvironmentPojo> environmentPojos = this.baseMapper.dropDown(environmentVo);
        return environmentPojos.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EnvironmentPojo::getId))), ArrayList::new
                )
        );
    }


    @Override
    public List<Integer> findByName(Integer environmentId) {
        List<Integer> list = new ArrayList<>();
        if (environmentId == null) {
            return list;
        }
        Environment environmentBean = this.baseMapper.selectById(environmentId);
        if (environmentBean == null) {
            return list;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", environmentBean.getName());
        List<Environment> environments = this.baseMapper.selectByMap(paramMap);
        if (CollectionUtils.isEmpty(environments)) {
            return list;
        }
        for (Environment environment : environments) {
            list.add(environment.getId());
        }
        return list;
    }

    @Override
    public List<DropDownPojo> addDropDown(DropDownVo dropDownVo) {
        Integer type = dropDownVo.getType();
        List<Environment> list = new ArrayList<>();
        List<DropDownPojo> resultList = new ArrayList<>();
        QueryWrapper<Environment> queryWrapper = new QueryWrapper<>();
        if (type == null) {
            //查询所有
            list = this.baseMapper.selectList(queryWrapper);
        }
        //根据系统查询所有环境
        if (type != null && type == 1) {
            //查询所有
            Integer id = dropDownVo.getId();
            List<Integer> envIds = relSystemEnvironmentService.findBySystemId(id);
            list = this.baseMapper.selectBatchIds(envIds);
        }

/*        if (type != null && type == 3) {
            //根据服务查询所有环境id
            Integer id = dropDownVo.getId();
            List<Integer> envIds = relEnvironmentServiceService.findByServiceId(id);
            list = this.baseMapper.selectBatchIds(envIds);
        }*/
        if (CollectionUtils.isEmpty(list)) {
            return resultList;
        }
        for (Environment environment : list) {
            DropDownPojo dropDownPojo = new DropDownPojo();
            BeanUtil.copyProperties(environment, dropDownPojo);
            resultList.add(dropDownPojo);
        }
        return resultList;
    }

}
